package com.xbongbong.saas.help;

import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OtherIncomeSheetTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.service.toolbox.statistic.help.SystemChartHelp;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author: 汪腾伟
 * @date: Created in 2021/11/18 15:21
 * @description：  其他收入单的帮助类
 */
@Component
public class SaasOtherIncomeHelp {

    @Resource
    private SystemChartHelp systemChartHelp;

    /**
     * 计算其他收入单已经红冲的总金额，即求和关联原始收入单id为sheetId的其他收入单的红冲金额
     * 注：此方法未对红冲金额求正值，因此此时的红冲金额还为负数
     * @param corpid 公司id
     * @param sheetId 收入单id
     * @return double
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public double sumRedAmountBySheet(String corpid, Long sheetId) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder4LinkRed(corpid, Collections.singletonList(sheetId));
        //聚合得到该条其他收入单（sheetId）关联的已红冲收入单总额
        return systemChartHelp.getDouble4Total(IndexTypeEnum.IDX_SAAS_OTHER_INCOME, boolQueryBuilder, OtherIncomeEnum.getAttrConnectData(OtherIncomeEnum.AMOUNT));
    }

    /**
     * 原始收入单的关联红冲收入单的查询条件
     * @param corpid 公司id
     * @param sheetIdIn 原单id集合
     * @return org.elasticsearch.index.query.BoolQueryBuilder
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private BoolQueryBuilder getBoolQueryBuilder4LinkRed(String corpid, List<Long> sheetIdIn) {
        // 查询该收入计划下面关联的所有收入单
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        //限制关联原始收入单id为sheetId
        boolQueryBuilder.filter(termsQuery(OtherIncomeEnum.getEsAttr4Keyword(OtherIncomeEnum.ORIGIN_ID), sheetIdIn));
        //只读红冲类型收入单
        boolQueryBuilder.filter(termsQuery(OtherIncomeEnum.getEsAttr4Keyword(OtherIncomeEnum.SHEET_TYPE_OTHER), OtherIncomeSheetTypeEnum.getRedCodeList()));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        return boolQueryBuilder;
    }
}
